//
//  EditItemDetailViewController.m
//  CS Inventory Manager
//
//  Created by Billy Zoellers on 3/8/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "EditItemDetailViewController.h"
#import "ModelSelectionNavViewController.h"
#import "ItemDetailViewController.h"
#import "InventoryViewController.h"
#import "AppDelegate.h"
#import "Type.h"

@interface EditItemDetailViewController ()

@end

@implementation EditItemDetailViewController
@synthesize theItem,inAssetID,inCost,inNotes,inValue,inSerial,inLocation,modelSelectPopover;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)saveButton:(id)sender {
    if ((inLocation.text.length != 0)&&(inAssetID.text.length !=0)&&(inSerial.text.length != 0)&&(inCost.text.length != 0)&&(inValue.text.length != 0)) {
        // save to DB
        //
        
        // generate the URL and use %20 encoding
        
        NSString *uid = [NSString stringWithFormat:@"%d",[theItem itemId]];
        NSString *status = [NSString stringWithFormat:@"1"];
        
        if (!inNotes.text) {
            // stop the (null) from getting pushed
            inNotes.text = @"";
        }
        
        NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/item.php?secret=pass&id=%@&assetno=%@&serialno=%@&cost=%@&value=%@&notes=%@&status=%@&mid=%i&location=%@",uid,inAssetID.text,inSerial.text,inCost.text,inValue.text,inNotes.text,status,[theItem mid],inLocation.text];
        NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSLog(@"The url is: >>>>>%@<<<<<", final);
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
        
        // make web request and catch error
        NSError * e;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
        
        // log the value returned from the web server
        NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"return from web: %@", value);
        
        if ([uid isEqualToString:@"0"]) {
            // this was a new item, get the ID back
            int newID = [[[value componentsSeparatedByString:@"*"] objectAtIndex:1] integerValue];
            NSLog(@"Got back from web: %i", newID);
            [theItem setItemId:newID];
        }
        
        
        // save locally!!!
        [theItem setAssetId:inAssetID.text];
        [theItem setSerialNo:inSerial.text];
        [theItem setCost:[inCost.text doubleValue]];
        [theItem setItemValue:[inValue.text doubleValue]];
        [theItem setNotes:inNotes.text];
        [theItem setLocation:inLocation.text];
        
        // reload the tables to show whatever changes were made
        if ([_delegate isKindOfClass:[ItemDetailViewController class]]) {
            // this means we're doing an edit, so we need to push two reloads!
            [[self.delegate tableView] reloadData];
            [[[self.delegate delegate] tableView] reloadData];
            
        } else {
            // this is the maker I was talking about..
            
            // we're adding, so the delegate is the IVC and we only reload the IVC
            [[self.delegate tableView] reloadData];
            
        }
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (IBAction)cancelButton:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Text Field Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == inLocation) {
        [inAssetID becomeFirstResponder];
    } else if (theTextField == inAssetID) {
        [inSerial becomeFirstResponder];
    } else if (theTextField == inSerial) {
        [inCost becomeFirstResponder];
    } else if (theTextField == inCost) {
        [inValue becomeFirstResponder];
    } else if (theTextField == inValue) {
        [inNotes becomeFirstResponder];
    } else if (theTextField == inNotes) {
        [inNotes resignFirstResponder];
    }
    
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    
   return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"editItemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // make a text field
    UITextField *inputTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 10, 530, 30)];
    inputTextField.adjustsFontSizeToFitWidth = YES;
    inputTextField.textColor = [UIColor blackColor];
    inputTextField.backgroundColor = [UIColor clearColor];
    inputTextField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
    inputTextField.autocapitalizationType = UITextAutocapitalizationTypeWords;
    inputTextField.tag = 0;
    inputTextField.clearButtonMode = UITextFieldViewModeAlways;
    [inputTextField setEnabled: YES];
    
    // Configure the cell...
    switch ([indexPath section]) {
        case 0:
            // first section
            cell.textLabel.text = @"Model";
            cell.detailTextLabel.text = [[self theItem] model];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;

            break;
        case 1:
            // second section
            switch ([indexPath row]) {
                case 0:
                    cell.textLabel.text = @"Location";
                    inputTextField.text = [[self theItem] location];
                    inputTextField.keyboardType = UIKeyboardTypeDefault;
                    inputTextField.returnKeyType = UIReturnKeyNext;
                    self.inLocation = inputTextField;
                    break;
                case 1:
                    cell.textLabel.text = @"Asset ID";
                    inputTextField.text = [[self theItem] assetId];
                    inputTextField.keyboardType = UIKeyboardTypeDefault;
                    inputTextField.returnKeyType = UIReturnKeyNext;
                    self.inAssetID = inputTextField;
                    break;
                case 2:
                    cell.textLabel.text = @"Serial #";
                    inputTextField.text = [[self theItem] serialNo];
                    inputTextField.keyboardType = UIKeyboardTypeDefault;
                    inputTextField.returnKeyType = UIReturnKeyNext;
                    self.inSerial = inputTextField;
                    break;
                case 3:
                    cell.textLabel.text = @"Cost";
                    if ([theItem cost]) {
                        inputTextField.text = [NSString stringWithFormat:@"%.02f",[[self theItem] cost]];
                    }
                    inputTextField.keyboardType = UIKeyboardTypeNumberPad;
                    inputTextField.returnKeyType = UIReturnKeyNext;
                    self.inCost = inputTextField;
                    break;
                case 4:
                    cell.textLabel.text = @"Value";
                    if ([theItem itemValue]) {
                        inputTextField.text = [NSString stringWithFormat:@"%.02f",[[self theItem] itemValue]];
                    }
                    inputTextField.keyboardType = UIKeyboardTypeNumberPad;
                    inputTextField.returnKeyType = UIReturnKeyNext;
                    self.inValue = inputTextField;
                    break;
                case 5:
                    cell.textLabel.text = @"Notes";
                    inputTextField.text = [[self theItem] notes];
                    inputTextField.keyboardType = UIKeyboardTypeDefault;
                    inputTextField.returnKeyType = UIReturnKeyDone;
                    self.inNotes = inputTextField;
                    break;
            }
            
            // add the text field to the cell
            cell.detailTextLabel.text = @"";
            inputTextField.delegate = self;
            [cell.contentView addSubview:inputTextField];
            
            break;
    }
    
    inputTextField = nil;
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"didSelect with section: %i and row %i",indexPath.section,indexPath.row);
    if (indexPath.section == 0 && indexPath.row == 0) {
        // don't leave the table cell blue
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        [self performSegueWithIdentifier:@"ModelPopover" sender:theItem];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    ModelSelectionNavViewController *nextController = segue.destinationViewController;
    [nextController setTheItem
     :sender];
    [nextController setDelegate:self];
    
    modelSelectPopover = [(UIStoryboardPopoverSegue *)segue popoverController];
    
}

- (void)closePopover {
    
    // Only refresh the top seciton with "Model"
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0]
                  withRowAnimation:UITableViewRowAnimationNone];
    
    [modelSelectPopover dismissPopoverAnimated:YES];
    
}


@end
